package com.itboye.mengwu.app.ui.web;

import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.object.BaseActivity;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.ui.main.GoodsDetailActivity;
import com.itboye.mengwu.app.ui.roof.DaPeiGouDetailActivity;
import com.itboye.mengwu.buy.ui.PayTypeActivity;
import com.itboye.mengwu.data.model.BuyBean;
import com.itboye.mengwu.data.model.BuyBean.PayInfo;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.common.message.Log;

public class WebActivity extends BaseActivity implements Observer,
		OnClickListener {

	WebView webview;
	TextView txt_title;
	private String urls;
	private String title;
	ImageView back, img_other;
	ProgressBar myProgressBar;
	WebSettings settings;
	StringBuilder builder = new StringBuilder();
	String pid;
	String groupid;
	String urlString = "com.moodwo.mengwu://?type=MENGWU_PRODUCT_DETAIL&pid=";
	private String APP_ID = "wxae95316b3a4998a6";
	private String QQAPP_ID = "1105450171";
	Tencent mTencent;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_web;
	}

	@Override
	public void onMyCreate() {
		img_other.setVisibility(View.GONE);
		title = getIntent().getStringExtra("title");
		txt_title.setText(title);
		mTencent = Tencent.createInstance(QQAPP_ID,
				this.getApplicationContext());
		urls = getIntent().getStringExtra("url");
		settings = webview.getSettings();
		settings.setSupportZoom(true);
		settings.setJavaScriptEnabled(true);
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		if (urls == null) {
			urls = "http://www.baidu.com";
		}
		IntentFilter filter = new IntentFilter("finish");
		registerReceiver(receiver, filter);

		webview.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
				builder = new StringBuilder();
				builder.append(url);
				Log.e("hu", "url==" + url);
				if (url.contains("MENGWU_PRODUCT_DETAIL")) {
					if (builder.indexOf("pid=") != -1) {
						groupid = builder.substring(builder.lastIndexOf("="),
								builder.length());
						pid = builder.substring(builder.indexOf("pid=") + 4,
								builder.lastIndexOf("&"));
						Intent intent = new Intent(WebActivity.this,
								GoodsDetailActivity.class);
						intent.putExtra("pid", pid);
						Log.e("hu", "pid==" + pid);
						startActivity(intent);
						// view.loadUrl("com.moodwo.mengwu://?type=MENGWU_PRODUCT_DETAIL&pid="
						// + pid + "&groupid=" + groupid);
					}
				} else if (url.contains("MENGWU_ALIPAY_SCOREGOODS")) {
					int index = url.indexOf("code");
					int endIndex = url.indexOf("&name");
					int descStartIndex = url.indexOf("desc");
					int descEndIndex = url.indexOf("&total_price");
					int priceStartIndex = url.indexOf("total_price");
					int priceEndIndex = url.indexOf("&key");
					String code = url.substring(index + 5, endIndex);
					String desc = url.substring(descStartIndex + 5,
							descEndIndex);
					String price = url.substring(priceStartIndex + 12,
							priceEndIndex);
					System.out.println("codecode--------??>>" + "code:" + code
							+ "desc:" + desc + "price:" + price);
					Intent intent = new Intent(WebActivity.this,
							PayTypeActivity.class);
					intent.putExtra("type", "aliy");
					BuyBean buyBean = new BuyBean();
					PayInfo payInfo = new PayInfo();
					buyBean.setPayInfo(payInfo);
					payInfo.setCode(code);
					payInfo.setTotalPrice(price);
					payInfo.setDesc(desc);
					intent.putExtra("model", buyBean);
					startActivity(intent);
				} else if (url.contains("MENGWU_WXPAY_SCOREGOODS")) {
					int index = url.indexOf("code");
					int endIndex = url.indexOf("&name");
					int descStartIndex = url.indexOf("desc");
					int descEndIndex = url.indexOf("&total_price");
					int priceStartIndex = url.indexOf("total_price");
					int priceEndIndex = url.indexOf("&key");
					String code = url.substring(index + 5, endIndex);
					String desc = url.substring(descStartIndex + 5,
							descEndIndex);
					String price = url.substring(priceStartIndex + 12,
							priceEndIndex);
					System.out.println("codecode--------??>>" + "code:" + code
							+ "desc:" + desc + "price:" + price);
					Intent intent = new Intent(WebActivity.this,
							PayTypeActivity.class);
					BuyBean buyBean = new BuyBean();
					PayInfo payInfo = new PayInfo();
					buyBean.setPayInfo(payInfo);
					payInfo.setCode(code);
					payInfo.setTotalPrice(price);
					payInfo.setDesc(desc);
					intent.putExtra("model", buyBean);
					intent.putExtra("type", "wx");
					startActivity(intent);
				} else if (url.contains("MENGWU_SHARE_WECHAT")) {
					final IWXAPI api = WXAPIFactory.createWXAPI(
							WebActivity.this, APP_ID, true);
					api.registerApp(APP_ID);
					api.openWXApp();
					int index = url.indexOf("idcode=");
					url.substring(index + 7, url.length() - 1);
					String text = "我的邀请码:"
							+ url.substring(index + 7, url.length());
					WXTextObject textObj = new WXTextObject();
					textObj.text = text;
					WXMediaMessage msg = new WXMediaMessage(textObj);
					msg.mediaObject = textObj;
					msg.description = text;
					SendMessageToWX.Req req = new SendMessageToWX.Req();
					req.transaction = String.valueOf(System.currentTimeMillis());
					req.message = msg;
					req.scene = SendMessageToWX.Req.WXSceneSession;
					api.sendReq(req);

				} else if (url.contains("MENGWU_SHARE_QQ")) {
					final Bundle params = new Bundle();
					int index = url.indexOf("idcode=");
					params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
							QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
					params.putString(QQShare.SHARE_TO_QQ_TITLE, "萌屋");
					params.putString(QQShare.SHARE_TO_QQ_SUMMARY,
							"我的邀请码：" + url.substring(index + 7, url.length()));
					params.putString(QQShare.SHARE_TO_QQ_TARGET_URL,
							"https://www.baidu.com");
					params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
							"http://imgcache.qq.com/qzone/space_item/pre/0/66768.gif");
					params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "萌屋");
					// params.putString(QQShare.SHARE_TO_QQ_APP_NAME,
					// "森森休闲");//应用名
					// params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
					mTencent.shareToQQ(WebActivity.this, params,
							new IUiListener() {

								@Override
								public void onError(UiError arg0) {
									// TODO Auto-generated method stub
									Log.e("hu", arg0.errorDetail + "");
									Log.e("hu", arg0.errorMessage + "");
									Log.e("hu", arg0.errorCode + "");
									Log.e("hu", arg0.toString() + "");
									Toast.makeText(getApplicationContext(),
											"分享失败，请重试", 0).show();
								}

								@Override
								public void onComplete(Object arg0) {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(),
											"分享完成", 0).show();
								}

								@Override
								public void onCancel() {
									// TODO Auto-generated method stub
									Toast.makeText(getApplicationContext(),
											"已取消", 0).show();
								}
							});
				} else if (url.contains("MENGWU_PRODUCT_PACKAGE")) {// 跳转搭配购详情
					int index = url.indexOf("&packageid");
					String packageId = url.substring(url.length() - 1,
							url.length());
					System.out.println(packageId + ">>>>>>>>>>packageId");
					Intent intent = new Intent(MainApplication.context,
							DaPeiGouDetailActivity.class);
					intent.putExtra("packageId", packageId);
					startActivity(intent);
				} else {
					view.loadUrl(url);
				}

				return true;
			}
		});

		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					myProgressBar.setVisibility(View.GONE);
				} else {
					if (View.GONE == myProgressBar.getVisibility()) {
						myProgressBar.setVisibility(View.VISIBLE);
					}
					myProgressBar.setProgress(newProgress);
				}
				super.onProgressChanged(view, newProgress);
			}

		});
		webview.loadUrl(urls);

	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// Intent intent2 = new Intent("set");
			// intent2.putExtra("index", 3);
			// sendBroadcast(intent2);
			finish();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
			webview.goBack(); // goBack()表示返回WebView的上一页面
			return true;
		} else {
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
}
